local skynet = require "skynet"
local gateserver = require "snax.gateserver"
local netpack = require "skynet.netpack"
local crypt = require "skynet.crypt"
local socketdriver = require "skynet.socketdriver"

local assert = assert
local b64encode = crypt.base64encode
local b64decode = crypt.base64decode

--[[

Protocol:

	All the number type is big-endian

	Shakehands (The first package)

	Client -> Server :

	base64(uid)@base64(server)#base64(subid):index:base64(hmac)

	Server -> Client

	XXX ErrorCode
		404 User Not Found
		403 Index Expired
		401 Unauthorized
		400 Bad Request
		200 OK

	Req-Resp

	Client -> Server : Request
		word size (Not include self)
		string content (size-4)
		dword session

	Server -> Client : Response
		word size (Not include self)
		string content (size-5)
		byte ok (1 is ok, 0 is error)
		dword session

API:
	server.userid(username)
		return uid, subid, server

	server.username(uid, subid, server)
		return username

	server.login(username, secret)
		update user secret

	server.logout(username)
		user logout

	server.ip(username)
		return ip when connection establish, or nil

	server.start(conf)
		start server

Supported skynet command:
	kick username (may used by loginserver)
	login username secret  (used by loginserver)
	logout username (used by agent)

Config for server.start:
	conf.expired_number : the number of the response message cached after sending out (default is 128)
	conf.login_handler(uid, secret) -> subid : the function when a new user login, alloc a subid for it. (may call by login server)
	conf.logout_handler(uid, subid) : the functon when a user logout. (may call by agent)
	conf.kick_handler(uid, subid) : the functon when a user logout. (may call by login server)
	conf.request_handler(username, session, msg) : the function when recv a new request.
	conf.register_handler(servername) : call when gate open
	conf.disconnect_handler(username) : call when a connection disconnect (afk)
]]

local server = {}

skynet.register_protocol {
	name = "client",
	id = skynet.PTYPE_CLIENT,
}

local user_online = {} -- { uid : uid, secret, ip, fd, resp{} }
local handshake = {}
local connection = {} -- { fd : user_online }

function server.userid(username)
	-- base64(uid)@base64(server)#base64(subid)
	local uid, servername, subid = username:match "([^@]*)@([^#]*)#(.*)"
	return b64decode(uid), b64decode(subid), b64decode(servername)
end

function server.username(uid, subid, servername)
	return string.format("%d@%s#%s", b64encode(uid), b64encode(servername), b64encode(tostring(subid)))
end

function server.logout(uid)
	local u = user_online[uid]
	user_online[uid] = nil

	if u.fd then
		if connection[u.fd] then
			gateserver.closeclient(u.fd)
			connection[u.fd] = nil
		end
	end
end

function server.login(uid, secret)
	assert(user_online[uid] == nil)
	
	user_online[uid] = {
		uid = uid, 
		secret = secret,
		handshake_index = 0, 

		ip = nil, 
		fd = nil, 
		response = {},	-- response cache
	}
end

function server.ip(uid)
	local u = user_online[uid]
	
	if u and u.fd then
		return u.ip
	end
end

function server.start(conf)
	local expired_number = conf.expired_number or 128

	local handler = {}

	local CMD = {
		login = assert(conf.login_handler),
		logout = assert(conf.logout_handler),
		kick = assert(conf.kick_handler),

		command = assert(conf.command_handler),
	}

	function handler.warning(fd, size)
		logger.warn("gated", "socket data size exceeded fd", fd, "size", size)
	end 

	function handler.command(cmd, source, ...)
		local f, result 
		if CMD[cmd] then 
			f = CMD[cmd] 
			result = f(...)
		else 
			f = CMD.command 
			result = f(cmd, source, ...)
		end 

		return result 
	end

	-- source : watchdog
	function handler.open(source, gateconf)
		local servername = assert(gateconf.servername)
		local loginservice = gateconf.loginservice
		return conf.register_handler(source, loginservice, servername)
	end

	function handler.connect(fd, addr)
		handshake[fd] = addr
		gateserver.openclient(fd)
	end

	function handler.disconnect(fd)
		handshake[fd] = nil
		local c = connection[fd]
		if c then
			if conf.disconnect_handler then
				conf.disconnect_handler(c.uid)
			end
			-- double check, conf.disconnect_handler may close fd
			if connection[fd] then
				c.fd = nil
				connection[fd] = nil
				gateserver.closeclient(fd)
			end
		end
	end

	handler.error = handler.disconnect

	local request_handler = assert(conf.request_handler)
	local auth_handler = assert(conf.auth_handler)

	-- atomic , no yield
	local function do_auth(fd, message, addr)
		-- format uid@base64(servername)#index:base64(hmac)
		local uid, servername, index, hmac = string.match(message, "([^@]*)@([^#]*)#([^:]*):(.*)")

		uid = tonumber(uid) 
		index = tonumber(index)
		hmac = crypt.base64decode(hmac)

		local u = user_online[uid]
		
		if u == nil then
			return "404 User Not Found"
		end
		local idx = assert(index)

		if idx <= u.handshake_index then
			return "403 Index Expired"
		end

		local text = string.format("%d@%s#%d", uid, servername, index)

		local v = crypt.hmac_hash(u.secret, text)	-- equivalent to crypt.hmac64(crypt.hashkey(text), u.secret)
		
		if v ~= hmac then
			return "401 Unauthorized"
		end

		u.handshake_index = idx
		u.fd = fd
		u.ip = addr

		connection[fd] = u
	end

	local function auth(fd, addr, msg, sz)
		local message = netpack.tostring(msg, sz)
		local ok, result = pcall(do_auth, fd, message, addr)
		if not ok then
			logger.warn("gated", "bad request", message)
			-- skynet.error(result)
			result = "400 Bad Request"
		end

		local close = result ~= nil

		if result == nil then
			result = "200 OK"
		end

		-- notify client auth result 
		socketdriver.send(fd, netpack.pack(result))

		if close then
			-- auth failed 
			gateserver.closeclient(fd)
		else 
			-- auth success 
			local u = connection[fd] 
			if u then 
				local uid = u.uid
				local fd = u.fd
				local ip = u.ip 

				auth_handler(uid, fd, ip)
			else 
				logger.error("gated", "auth verify success but no associte user found for fd", fd)
				-- error("aut verify succ, but not associted with user by fd ~")
			end 
		end 
	end

	function handler.message(fd, msg, sz)
		local addr = handshake[fd]
		if addr then
			handshake[fd] = nil

			auth(fd, addr, msg, sz)
		else
			local u = assert(connection[fd], "invalid fd")
			local msg = netpack.tostring(msg, sz)
			request_handler(u.uid, msg, fd)
		end
	end

	return gateserver.start(handler)
end

return server
